' Written by Thomas Berezansky, Merrimack Valley Library Consortium
' Printer Information code from Wade Brooks (http://wadewb.com)

'Copyright (c) 2009, Merrimack Valley Library Consortium
'Copyright (c) 2012, Jay Miley
'All rights reserved.
'
'Redistribution and use in source and binary forms, with or without modification, are permitted
'provided that the following conditions are met:
'
'    * Redistributions of source code must retain the above copyright notice, this list of
'      conditions and the following disclaimer.
'    * Redistributions in binary form must reproduce the above copyright notice, this list of
'      conditions and the following disclaimer in the documentation and/or other materials
'      provided with the distribution.
'    * Neither the name of the Merrimack Valley Library Consortium nor the names of its
'      contributors may be used to endorse or promote products derived from this software without
'      specific prior written permission.
'
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
'IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
'AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
'CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
'CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
'SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
'THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
'OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
'POSSIBILITY OF SUCH DAMAGE.

Imports System.Xml
Imports System.Drawing.Printing
Imports System.Runtime.InteropServices
Imports System.IO

Public Class frmSettings

    <DllImport("winspool.drv", EntryPoint:="OpenPrinterW", CharSet:=CharSet.Auto, SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Private Shared Function OpenPrinter(ByVal pPrinterName As String, ByRef hPrinter As IntPtr, ByVal pDefault As IntPtr) As Boolean
    End Function

    <DllImport("winspool.drv", CharSet:=CharSet.Auto, SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Private Shared Function ClosePrinter(ByVal hPrinter As IntPtr) As Boolean
    End Function

    <DllImport("winspool.drv", EntryPoint:="GetPrinterW", CharSet:=CharSet.Auto, SetLastError:=True, ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
    Private Shared Function GetPrinter(ByVal hPrinter As IntPtr, ByVal dwLevel As Integer, ByVal pPrinter As IntPtr, ByVal cbBuf As Integer, ByRef pcbNeeded As Integer) As Boolean
    End Function

    'Printer Info structure
    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> Public Structure PRINTER_INFO_2
        Dim pServerName As String
        Dim pPrinterName As String
        Dim pShareName As String
        Dim pPortName As String
        Dim pDriverName As String
        Dim pComment As String
        Dim pLocation As String
        Dim pDevMode As Integer
        Dim pSepFile As String
        Dim pPrintProcessor As String
        Dim pDatatype As String
        Dim pParameters As String
        Dim pSecurityDescriptor As Integer
        Dim Attributes As Integer
        Dim Priority As Integer
        Dim DefaultPriority As Integer
        Dim StartTime As Integer
        Dim UntilTime As Integer
        Dim Status As Integer
        Dim cJobs As Integer
        Dim AveragePPM As Integer
    End Structure

    ' Overall settings - Loaded from config file
    Private myPrinter As String = ""
    Private myWhiteSpaceTop As Integer = 0
    Private myWhiteSpaceBottom As Integer = 1

    ' Hold Slip settings - Loaded from config file
    Private myHoldDate As Integer = 2
    Private myHoldDateAdd As Integer = 7
    Private myHoldDateYear As Boolean = False
    Private myHoldPatronBarcodeMask As Integer = 0
    Private myHoldWhiteSpaceBottom As Integer = 0
    Private myHoldNamePosition As Integer = 1
    Private myHoldCallSlips = 0
    Private myHoldLastNameSize As Integer = 2
    Private myHoldFirstNameSize As Integer = 1

    ' Checkout Slip settings - Loaded from config file
    Private myCheckoutPatronBarcodeMask As Integer = 0
    Private myCheckoutDueDates As Integer = 0

    ' Checkin Slip settings - Loaded from config file
    Private myCheckinPatronBarcodeMask As Integer = 0

    ' Transit Slip settings - Loaded from config file
    Private myTransitWhiteSpaceBottom As Integer = 0
    Private myTransitMiniWhiteSpaceBottom As Integer = 0

    ' Payment Slip settings - Loaded from config file
    Private myPaymentSlips As Integer = 0
    Private myPaymentPatronBarcodeMask As Integer = 0

    Dim settingsDoc As New XmlDocument
    Dim savefilename As String = String.Empty

    Private Sub frmSettings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim isAgencyFile As Boolean = False
        If Environment.GetCommandLineArgs.Length > 1 Then
            If OpenSettingsDoc(Environment.GetCommandLineArgs(1), isAgencyFile) Then
                If isAgencyFile Then
                    Dim agencyForm As New frmAgencies
                    If frmAgencies.loadFile(Environment.GetCommandLineArgs(1)) Then
                        Me.Hide()
                        frmAgencies.ShowDialog()
                        Me.Close()
                        Exit Sub
                    Else
                        frmAgencies.Close()
                    End If
                End If
                Me.Text = "Symphony Receipt Printer Settings Utility - " & Environment.GetCommandLineArgs(1)
                savefilename = Environment.GetCommandLineArgs(1)
            End If
            isAgencyFile = False
        ElseIf OpenSettingsDoc("settings.xml", isAgencyFile) Then
            If isAgencyFile Then
                MsgBox("settings.xml appears to be an agencies file - This is likely a mistake. Defaults are being loaded.")
                OpenSettingsDoc(Nothing, False)
            Else
                Me.Text = "Symphony Receipt Printer Settings - settings.xml"
                savefilename = "settings.xml"
            End If
            isAgencyFile = False
        ElseIf OpenSettingsDoc(My.Application.Info.DirectoryPath & "\settings.xml", isAgencyFile) Then
            If isAgencyFile Then
                MsgBox(My.Application.Info.DirectoryPath & "\settings.xml appears to be an agencies file - This is likely a mistake. Defaults are being loaded.")
                OpenSettingsDoc(Nothing, False)
            Else
                Me.Text = "Symphony Receipt Printer Settings - " & My.Application.Info.DirectoryPath & "\settings.xml"
                savefilename = My.Application.Info.DirectoryPath & "\settings.xml"
            End If
        Else
            OpenSettingsDoc(Nothing, False)
        End If
        LoadSettingsDoc()
        PopulateInstalledPrinters()
    End Sub

    Private Function OpenSettingsDoc(ByRef filename As String, ByRef isAgencyFile As Boolean) As Boolean
        If filename Is Nothing Then
            settingsDoc.LoadXml("<HZReceipt />")
            Return True
        Else
            Try
                settingsDoc.Load(filename)
                If Not settingsDoc.SelectSingleNode("Agencies") Is Nothing Then
                    isAgencyFile = True
                End If
                Return True
            Catch ex As Exception
                Return False
            End Try
        End If
    End Function

    Private Sub LoadSettingsDoc()
        Dim configNode As XmlNode
        configNode = settingsDoc.SelectSingleNode("HZReceipt/Printer")
        If Not configNode Is Nothing Then
            myPrinter = configNode.InnerText.Trim
        End If
        'configNode = settingsDoc.SelectSingleNode("HZReceipt/ConfigHorizon")
        'If Not configNode Is Nothing Then
        '    chkConfigHorizon.Checked = configNode.InnerText.Trim.Equals("1")
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/CommonConfig")
        If Not configNode Is Nothing Then
            txtCommonLocation.Text = configNode.InnerText
            configNode = configNode.Attributes.GetNamedItem("replace")
            If Not configNode Is Nothing Then
                chkCommonConfigReplace.Checked = configNode.Value.Trim.Equals("1")
            End If
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/TopMessageFile")
        If Not configNode Is Nothing Then
            txtTopMessage.Text = configNode.InnerText.Trim
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/BottomMessageFile")
        If Not configNode Is Nothing Then
            txtBottomMessage.Text = configNode.InnerText.Trim
        End If
        'configNode = settingsDoc.SelectSingleNode("HZReceipt/PhoneNumber")
        'If Not configNode Is Nothing Then
        '    txtPhoneNumber.Text = configNode.InnerText.Trim
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/WhiteSpaceTop")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myWhiteSpaceTop)
        End If
        If myWhiteSpaceTop < 0 Then
            cboWhiteSpaceTop.SelectedIndex = 0
        ElseIf myWhiteSpaceTop > 5 Then
            cboWhiteSpaceTop.SelectedIndex = 5
        Else
            cboWhiteSpaceTop.SelectedIndex = myWhiteSpaceTop
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/WhiteSpaceBottom")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myWhiteSpaceBottom)
        End If
        If myWhiteSpaceBottom < 0 Then
            cboWhiteSpaceBottom.SelectedIndex = 0
        ElseIf myWhiteSpaceBottom > 5 Then
            cboWhiteSpaceBottom.SelectedIndex = 5
        Else
            cboWhiteSpaceBottom.SelectedIndex = myWhiteSpaceBottom
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/AgencyFile")
        If Not configNode Is Nothing Then
            txtAgencies.Text = configNode.InnerText.Trim
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/AutoCut")
        If Not configNode Is Nothing Then
            chkAutoCut.Checked = configNode.InnerText.Trim.Equals("1")
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/NamePosition")
        If Not configNode Is Nothing Then
            Select Case configNode.InnerText.Trim.ToLower
                Case "off"
                    myHoldNamePosition = 0
                Case "top"
                    myHoldNamePosition = 1
                Case "topflipped"
                    myHoldNamePosition = 2
                Case "bottom"
                    myHoldNamePosition = 3
                    ' Case Else
                    '    myHoldNamePosition = 0
            End Select
        End If
        cboHoldNamePosition.SelectedIndex = myHoldNamePosition

        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/LastNameSize")
        If Not configNode Is Nothing Then
            Select Case configNode.InnerText.Trim.ToLower
                Case "normal"
                    myHoldLastNameSize = 0
                Case "double"
                    myHoldLastNameSize = 1
                Case "triple"
                    myHoldLastNameSize = 2
            End Select
        End If
        cboLastNameSize.SelectedIndex = myHoldLastNameSize

        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/FirstNameSize")
        If Not configNode Is Nothing Then
            Select Case configNode.InnerText.Trim.ToLower
                Case "normal"
                    myHoldFirstNameSize = 0
                Case "double"
                    myHoldFirstNameSize = 1
                Case "triple"
                    myHoldFirstNameSize = 2
            End Select
        End If
        cboFirstNameSize.SelectedIndex = myHoldFirstNameSize

        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/ShowDate")
        If Not configNode Is Nothing Then
            Select Case configNode.InnerText.Trim.ToLower
                Case "left"
                    myHoldDate = 1
                Case "right"
                    myHoldDate = 2
                Case "center"
                    myHoldDate = 3
                Case Else
                    myHoldDate = 0
            End Select
        End If
        cboHoldDate.SelectedIndex = myHoldDate
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/DateAdd")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myHoldDateAdd)
        End If
        If myHoldDateAdd < 0 Then
            cboHoldDateAdd.SelectedIndex = 0
        ElseIf myHoldDateAdd > 14 Then
            cboHoldDateAdd.SelectedIndex = 14
        Else
            cboHoldDateAdd.SelectedIndex = myHoldDateAdd
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/DateYear")
        If Not configNode Is Nothing Then
            myHoldDateYear = configNode.InnerText.Trim.Equals("1")
        End If
        If myHoldDateYear Then
            rdoHoldDateYearOn.Checked = True
        Else
            rdoHoldDateYearOff.Checked = True
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/ShowPatronBarcode")
        'If Not configNode Is Nothing Then
        '    chkHoldPatronBarcode.Checked = configNode.InnerText.Trim.Equals("1")
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/MaskPatronBarcode")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myHoldPatronBarcodeMask)
        End If
        If myHoldPatronBarcodeMask < 0 Then
            cboHoldPatronMaskBarcode.SelectedIndex = 0
        ElseIf myHoldPatronBarcodeMask > 9 Then
            cboHoldPatronMaskBarcode.SelectedIndex = 9
        Else
            cboHoldPatronMaskBarcode.SelectedIndex = myHoldPatronBarcodeMask
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/ShowEMail")
        'If Not configNode Is Nothing Then
        '    chkHoldPatronEMail.Checked = configNode.InnerText.Trim.Equals("1")
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/ShowPhone")
        'If Not configNode Is Nothing Then
        '    chkHoldPatronPhone.Checked = configNode.InnerText.Trim.Equals("1")
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/PhoneLarger")
        If Not configNode Is Nothing Then
            chkHoldPatronPhoneSize.Checked = configNode.InnerText.Trim.Equals("1")
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/WhiteSpaceBottom")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myHoldWhiteSpaceBottom)
        End If
        If myHoldWhiteSpaceBottom < 0 Then
            cboHoldWhiteSpaceBottom.SelectedIndex = 0
        ElseIf myHoldWhiteSpaceBottom > 5 Then
            cboHoldWhiteSpaceBottom.SelectedIndex = 5
        Else
            cboHoldWhiteSpaceBottom.SelectedIndex = myHoldWhiteSpaceBottom
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/ShowOriginalDate")
        'If Not configNode Is Nothing Then
        '    chkHoldCircDate.Checked = configNode.InnerText.Trim.Equals("1")
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/HoldSlips/CallSlips")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myHoldCallSlips)
            If myHoldCallSlips < 0 Or myHoldCallSlips > 2 Then
                myHoldCallSlips = 0
            End If
        End If
        'cboHoldCallSlips.SelectedIndex = myHoldCallSlips
        configNode = settingsDoc.SelectSingleNode("HZReceipt/CheckOutSlips/AddPhone")
        'If Not configNode Is Nothing Then
        '    chkCheckOutAddPhone.Checked = configNode.InnerText.Trim.Equals("1")
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/CheckOutSlips/MaskPatronBarcode")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myCheckoutPatronBarcodeMask)
        End If
        If myCheckoutPatronBarcodeMask < 0 Then
            cboCheckOutMaskBarcode.SelectedIndex = 0
        ElseIf myCheckoutPatronBarcodeMask > 9 Then
            cboCheckOutMaskBarcode.SelectedIndex = 9
        Else
            cboCheckOutMaskBarcode.SelectedIndex = myCheckoutPatronBarcodeMask
        End If
        'configNode = settingsDoc.SelectSingleNode("HZReceipt/CheckOutSlips/EnhanceDueDates")
        'If Not configNode Is Nothing Then
        'chkCheckOutDueDates.Checked = configNode.InnerText.Trim.Equals("1")
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/CheckOutSlips/EnhanceDueDates")
        If Not configNode Is Nothing Then
            Select Case configNode.InnerText.Trim.ToLower
                Case "1"
                    myCheckoutDueDates = 1
                Case "2"
                    myCheckoutDueDates = 2
                Case Else
                    myCheckoutDueDates = 0
            End Select
        End If
        cboEnhanceDueDates.SelectedIndex = myCheckoutDueDates
        configNode = settingsDoc.SelectSingleNode("HZReceipt/CheckInSlips/AddPhone")
        If Not configNode Is Nothing Then
            chkCheckInAddPhone.Checked = configNode.InnerText.Trim.Equals("1")
        End If
        'configNode = settingsDoc.SelectSingleNode("HZReceipt/CheckInSlips/MaskPatronBarcode")
        'If Not configNode Is Nothing Then
        '    Integer.TryParse(configNode.InnerText, myCheckinPatronBarcodeMask)
        'End If
        'If myCheckinPatronBarcodeMask < 0 Then
        '    cboPaymentMaskBarcode.SelectedIndex = 0
        'ElseIf myCheckoutPatronBarcodeMask > 9 Then
        '    cboPaymentMaskBarcode.SelectedIndex = 9
        'Else
        '    cboPaymentMaskBarcode.SelectedIndex = myCheckinPatronBarcodeMask
        'End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/PaymentSlips/MaskUserBarcode")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myPaymentPatronBarcodeMask)
        End If
        If myPaymentPatronBarcodeMask < 0 Then
            cboPaymentMaskBarcode.SelectedIndex = 0
        ElseIf myPaymentPatronBarcodeMask > 9 Then
            cboPaymentMaskBarcode.SelectedIndex = 9
        Else
            cboPaymentMaskBarcode.SelectedIndex = myPaymentPatronBarcodeMask
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/PaymentSlips/Prompt")
        If Not configNode Is Nothing Then
            chkPaymentSlipPrompt.Checked = configNode.InnerText.Trim.Equals("1")
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/CheckInSlips/Disable")
        If Not configNode Is Nothing Then
            chkCheckInOff.Checked = configNode.InnerText.Trim.Equals("1")
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/TransitSlips/WhiteSpaceBottom")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myTransitWhiteSpaceBottom)
        End If
        If myTransitWhiteSpaceBottom < 0 Then
            cboTransitWhiteSpaceBottom.SelectedIndex = 0
        ElseIf myTransitWhiteSpaceBottom > 5 Then
            cboTransitWhiteSpaceBottom.SelectedIndex = 5
        Else
            cboTransitWhiteSpaceBottom.SelectedIndex = myTransitWhiteSpaceBottom
        End If
        configNode = settingsDoc.SelectSingleNode("HZReceipt/TransitSlips/MiniWhiteSpaceBottom")
        If Not configNode Is Nothing Then
            Integer.TryParse(configNode.InnerText, myTransitMiniWhiteSpaceBottom)
        End If
        If myTransitMiniWhiteSpaceBottom < 0 Then
            cboTransitMiniWhiteSpaceBottom.SelectedIndex = 0
        ElseIf myTransitWhiteSpaceBottom > 5 Then
            cboTransitMiniWhiteSpaceBottom.SelectedIndex = 5
        Else
            cboTransitMiniWhiteSpaceBottom.SelectedIndex = myTransitMiniWhiteSpaceBottom
        End If
    End Sub

    Private Sub SaveSettingsDoc()
        Dim insertNode As XmlNode
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt")
        If insertNode Is Nothing Then ' Failure in document?
            settingsDoc.LoadXml("<HZReceipt />") ' Re-start with blank
            insertNode = settingsDoc.SelectSingleNode("/HZReceipt")
            If insertNode Is Nothing Then ' Failure AGAIN? Something is wrong.
                MsgBox("Could not load XML root!")
                Return
            End If
        End If
        insertReplaceValue(settingsDoc, insertNode, "Printer", cboDestPrinter.Text)
        'If chkConfigHorizon.Checked Then
        '    insertReplaceValue(settingsDoc, insertNode, "ConfigHorizon", "1")
        'Else
        '    insertReplaceValue(settingsDoc, insertNode, "ConfigHorizon", "0")
        'End If
        insertReplaceValue(settingsDoc, insertNode, "CommonConfig", txtCommonLocation.Text)
        Dim configNode As XmlNode = settingsDoc.SelectSingleNode("HZReceipt/CommonConfig")
        If Not configNode Is Nothing Then
            Dim attributeNode As XmlNode = settingsDoc.CreateAttribute("replace")
            If chkCommonConfigReplace.Checked Then
                attributeNode.Value = "1"
            Else
                attributeNode.Value = "0"
            End If
            configNode.Attributes.SetNamedItem(attributeNode)
        End If
        insertReplaceValue(settingsDoc, insertNode, "TopMessageFile", txtTopMessage.Text)
        insertReplaceValue(settingsDoc, insertNode, "BottomMessageFile", txtBottomMessage.Text)
        '    insertReplaceValue(settingsDoc, insertNode, "PhoneNumber", txtPhoneNumber.Text)
        insertReplaceValue(settingsDoc, insertNode, "WhiteSpaceTop", cboWhiteSpaceTop.SelectedIndex.ToString)
        insertReplaceValue(settingsDoc, insertNode, "WhiteSpaceBottom", cboWhiteSpaceBottom.SelectedIndex.ToString)
        insertReplaceValue(settingsDoc, insertNode, "AgencyFile", txtAgencies.Text)
        If chkAutoCut.Checked Then
            insertReplaceValue(settingsDoc, insertNode, "AutoCut", "1")
        Else
            insertReplaceValue(settingsDoc, insertNode, "AutoCut", "0")
        End If

        insertReplaceValue(settingsDoc, insertNode, "HoldSlips")
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt/HoldSlips")
        Select Case cboHoldNamePosition.SelectedIndex
            Case 0
                insertReplaceValue(settingsDoc, insertNode, "NamePosition", "off")
            Case 1
                insertReplaceValue(settingsDoc, insertNode, "NamePosition", "top")
            Case 2
                insertReplaceValue(settingsDoc, insertNode, "NamePosition", "topflipped")
            Case 3
                insertReplaceValue(settingsDoc, insertNode, "NamePosition", "bottom")
        End Select
        insertReplaceValue(settingsDoc, insertNode, "LastNameSize")
        Select Case cboLastNameSize.SelectedIndex
            Case 0
                insertReplaceValue(settingsDoc, insertNode, "LastNameSize", "normal")
            Case 1
                insertReplaceValue(settingsDoc, insertNode, "LastNameSize", "double")
            Case 2
                insertReplaceValue(settingsDoc, insertNode, "LastNameSize", "triple")
        End Select
        insertReplaceValue(settingsDoc, insertNode, "FirstNameSize")
        Select Case cboFirstNameSize.SelectedIndex
            Case 0
                insertReplaceValue(settingsDoc, insertNode, "FirstNameSize", "normal")
            Case 1
                insertReplaceValue(settingsDoc, insertNode, "FirstNameSize", "double")
            Case 2
                insertReplaceValue(settingsDoc, insertNode, "FirstNameSize", "triple")
        End Select
        insertReplaceValue(settingsDoc, insertNode, "ShowDate", cboHoldDate.Text.ToLower)
        insertReplaceValue(settingsDoc, insertNode, "DateAdd", cboHoldDateAdd.SelectedIndex.ToString)
        If rdoHoldDateYearOn.Checked Then
            insertReplaceValue(settingsDoc, insertNode, "DateYear", "1")
        Else
            insertReplaceValue(settingsDoc, insertNode, "DateYear", "0")
        End If
        'If chkHoldPatronBarcode.Checked Then
        '    insertReplaceValue(settingsDoc, insertNode, "ShowPatronBarcode", "1")
        'Else
        '    insertReplaceValue(settingsDoc, insertNode, "ShowPatronBarcode", "0")
        'End If
        insertReplaceValue(settingsDoc, insertNode, "MaskPatronBarcode", cboHoldPatronMaskBarcode.SelectedIndex.ToString)
        'If chkHoldPatronEMail.Checked Then
        '    insertReplaceValue(settingsDoc, insertNode, "ShowEMail", "1")
        'Else
        '    insertReplaceValue(settingsDoc, insertNode, "ShowEMail", "0")
        'End If
        'If chkHoldPatronPhone.Checked Then
        '    insertReplaceValue(settingsDoc, insertNode, "ShowPhone", "1")
        'Else
        '    insertReplaceValue(settingsDoc, insertNode, "ShowPhone", "0")
        'End If
        If chkHoldPatronPhoneSize.Checked Then
            insertReplaceValue(settingsDoc, insertNode, "PhoneLarger", "1")
        Else
            insertReplaceValue(settingsDoc, insertNode, "PhoneLarger", "0")
        End If
        insertReplaceValue(settingsDoc, insertNode, "WhiteSpaceBottom", cboHoldWhiteSpaceBottom.SelectedIndex.ToString)
        'If chkHoldCircDate.Checked Then
        '    insertReplaceValue(settingsDoc, insertNode, "ShowOriginalDate", "1")
        'Else
        '    insertReplaceValue(settingsDoc, insertNode, "ShowOriginalDate", "0")
        'End If
        'insertReplaceValue(settingsDoc, insertNode, "CallSlips", cboHoldCallSlips.SelectedIndex.ToString)
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt")
        insertReplaceValue(settingsDoc, insertNode, "CheckOutSlips")
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt/CheckOutSlips")
        'If chkCheckOutAddPhone.Checked Then
        '    insertReplaceValue(settingsDoc, insertNode, "AddPhone", "1")
        'Else
        '    insertReplaceValue(settingsDoc, insertNode, "AddPhone", "0")
        'End If
        insertReplaceValue(settingsDoc, insertNode, "MaskPatronBarcode", cboCheckOutMaskBarcode.SelectedIndex.ToString)
        'If chkCheckOutDueDates.Checked Then
        '    insertReplaceValue(settingsDoc, insertNode, "EnhanceDueDates", "1")
        'Else
        '    insertReplaceValue(settingsDoc, insertNode, "EnhanceDueDates", "0")
        'End If
        Select Case cboEnhanceDueDates.SelectedIndex
            Case 0
                insertReplaceValue(settingsDoc, insertNode, "EnhanceDueDates", "0")
            Case 1
                insertReplaceValue(settingsDoc, insertNode, "EnhanceDueDates", "1")
            Case 2
                insertReplaceValue(settingsDoc, insertNode, "EnhanceDueDates", "2")
        End Select
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt")
        insertReplaceValue(settingsDoc, insertNode, "CheckInSlips")
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt/CheckInSlips")
        If chkCheckInAddPhone.Checked Then
            insertReplaceValue(settingsDoc, insertNode, "AddPhone", "1")
        Else
            insertReplaceValue(settingsDoc, insertNode, "AddPhone", "0")
        End If
        'insertReplaceValue(settingsDoc, insertNode, "MaskPatronBarcode", cboPaymentMaskBarcode.SelectedIndex.ToString)
        If chkCheckInOff.Checked Then
            insertReplaceValue(settingsDoc, insertNode, "Disable", "1")
        Else
            insertReplaceValue(settingsDoc, insertNode, "Disable", "0")
        End If
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt")
        insertReplaceValue(settingsDoc, insertNode, "PaymentSlips")
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt/PaymentSlips")
        If chkPaymentSlipPrompt.Checked Then
            insertReplaceValue(settingsDoc, insertNode, "Prompt", "1")
        Else
            insertReplaceValue(settingsDoc, insertNode, "Prompt", "0")
        End If
        insertReplaceValue(settingsDoc, insertNode, "MaskUserBarcode", cboPaymentMaskBarcode.SelectedIndex.ToString)
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt")
        insertReplaceValue(settingsDoc, insertNode, "TransitSlips")
        insertNode = settingsDoc.SelectSingleNode("/HZReceipt/TransitSlips")
        insertReplaceValue(settingsDoc, insertNode, "WhiteSpaceBottom", cboTransitWhiteSpaceBottom.SelectedIndex.ToString)
        insertReplaceValue(settingsDoc, insertNode, "MiniWhiteSpaceBottom", cboTransitMiniWhiteSpaceBottom.SelectedIndex.ToString)
    End Sub

    Public Sub insertReplaceValue(ByRef xmlDoc As XmlDocument, ByRef parentNode As XmlNode, ByRef nodeName As String, Optional ByRef value As String = Nothing)
        Dim targetNode As XmlNode = parentNode.SelectSingleNode(nodeName)
        If targetNode Is Nothing Then
            targetNode = xmlDoc.CreateElement(nodeName)
            If Not value Is Nothing Then
                targetNode.InnerText = value
            End If
            parentNode.AppendChild(targetNode)
        ElseIf Not value Is Nothing Then
            targetNode.InnerText = value
        End If
    End Sub

    Private Sub PopulateInstalledPrinters()
        Dim strInstalledPrinter As String = String.Empty 'Installed printer
        Dim info As PRINTER_INFO_2
        Try
            cboDestPrinter.Items.Clear()

            ' Add list of installed printers found to the combo box.
            For Each strPrinter As String In PrinterSettings.InstalledPrinters
                info = GetPrinterInfo(strPrinter)
                If Not info.pPortName.Equals("\\.\pipe\HZReceipt") Then
                    cboDestPrinter.Items.Add(strPrinter)
                    If strPrinter = myPrinter Then
                        cboDestPrinter.SelectedIndex = cboDestPrinter.Items.Count - 1
                    End If
                End If
            Next

            If cboDestPrinter.Items.Count > 0 And cboDestPrinter.SelectedIndex = -1 Then
                cboDestPrinter.SelectedIndex = 0
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK)
        End Try
    End Sub

    Private Function GetPrinterInfo(ByVal sName As String) As PRINTER_INFO_2

        Dim hPrinter As IntPtr = IntPtr.Zero
        Dim pPrinterInfo As IntPtr = IntPtr.Zero
        Dim iNeed As Integer = -1
        Dim SizeOf As Integer = -1
        Try

            'Open printer object
            If (Not OpenPrinter(sName, hPrinter, IntPtr.Zero)) Then
                Marshal.ThrowExceptionForHR(System.Runtime.InteropServices.Marshal.GetHRForLastWin32Error())
            End If

            Try
                ' Get the number of bytes needed. 
                GetPrinter(hPrinter, 2, IntPtr.Zero, 0, iNeed)

                ' Allocate enough memory. 
                pPrinterInfo = Marshal.AllocHGlobal(iNeed)
                SizeOf = iNeed
                If (Not GetPrinter(hPrinter, 2, pPrinterInfo, SizeOf, iNeed)) Then
                    Marshal.ThrowExceptionForHR(System.Runtime.InteropServices.Marshal.GetHRForLastWin32Error())
                End If

                ' Now marshal the structure manually. 
                Dim PrinterInfo As PRINTER_INFO_2 = CType(Marshal.PtrToStructure(pPrinterInfo, GetType(PRINTER_INFO_2)), PRINTER_INFO_2)

                Return PrinterInfo
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK)
            Finally
                ' Close the printer object. 
                ClosePrinter(hPrinter)
                ' Deallocate the memory. 
                Marshal.FreeHGlobal(pPrinterInfo)
            End Try
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK)
        End Try
        Return New PRINTER_INFO_2()
    End Function

    Private Sub btnPickTopMessage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPickTopMessage.Click
        pickFileDialog.Filter = ""
        Try
            pickFileDialog.InitialDirectory = Path.GetDirectoryName(txtTopMessage.Text)
            pickFileDialog.FileName = Path.GetFileName(txtTopMessage.Text)
        Catch ex As Exception
            pickFileDialog.FileName = txtTopMessage.Text
        End Try
        If pickFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtTopMessage.Text = pickFileDialog.FileName
            pickFileDialog.FileName = ""
        End If
    End Sub

    Private Sub btnPickBottomMessage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPickBottomMessage.Click
        pickFileDialog.Filter = ""
        Try
            pickFileDialog.InitialDirectory = Path.GetDirectoryName(txtBottomMessage.Text)
            pickFileDialog.FileName = Path.GetFileName(txtBottomMessage.Text)
        Catch ex As Exception
            pickFileDialog.FileName = txtBottomMessage.Text
        End Try
        If pickFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtBottomMessage.Text = pickFileDialog.FileName
            pickFileDialog.FileName = ""
        End If
    End Sub

    Private Sub btnPickAgenciesFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPickAgenciesFile.Click
        pickFileDialog.Filter = "Agencies File|*.xml"
        Try
            pickFileDialog.InitialDirectory = Path.GetDirectoryName(txtAgencies.Text)
            pickFileDialog.FileName = Path.GetFileName(txtAgencies.Text)
        Catch ex As Exception
            pickFileDialog.FileName = txtAgencies.Text
        End Try
        If pickFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtAgencies.Text = pickFileDialog.FileName
            pickFileDialog.FileName = ""
        End If
    End Sub

    Private Sub cboHoldDate_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboHoldDate.SelectedIndexChanged
        lblHoldDateAdd.Enabled = cboHoldDate.SelectedIndex
        cboHoldDateAdd.Enabled = cboHoldDate.SelectedIndex
        lblHoldDateFormat.Enabled = cboHoldDate.SelectedIndex
        rdoHoldDateYearOff.Enabled = cboHoldDate.SelectedIndex
        rdoHoldDateYearOn.Enabled = cboHoldDate.SelectedIndex
    End Sub
    Private Sub cboHoldNamePosition_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboHoldNamePosition.SelectedIndexChanged
        lblLastNameSize.Enabled = cboHoldNamePosition.SelectedIndex
        cboLastNameSize.Enabled = cboHoldNamePosition.SelectedIndex
        lblFirstNameSize.Enabled = cboHoldNamePosition.SelectedIndex
        cboFirstNameSize.Enabled = cboHoldNamePosition.SelectedIndex
    End Sub
    'Private Sub chkHoldPatronBarcode_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    lblHoldPatronBarcodeMask.Enabled = chkHoldPatronBarcode.Checked
    '    cboHoldPatronMaskBarcode.Enabled = chkHoldPatronBarcode.Checked
    'End Sub

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        If savefilename.Length > 0 Then
            SaveSettingsDoc()
            settingsDoc.Save(savefilename)
        Else
            btnSaveAs_Click(sender, e)
        End If
    End Sub

    Private Sub btnSaveAs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveAs.Click
        If saveConfigDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
            SaveSettingsDoc()
            Try
                settingsDoc.Save(saveConfigDialog.FileName)
                savefilename = saveConfigDialog.FileName
                Me.Text = "Symphony Receipt Printer Settings - " & savefilename
            Catch ex As Exception
                MsgBox("Could not save: " & ex.Message, MsgBoxStyle.Critical, "Save Failure")
            End Try
        End If
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub btnAgencySlipMode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgencySlipMode.Click
        Dim agenciesdialog As New frmAgencies
        If agenciesdialog.loadFile(txtAgencies.Text) Then
            agenciesdialog.ShowDialog()
        ElseIf Not txtAgencies.Text.Equals("agencies.xml") And File.Exists("agencies.xml") Then
            If MsgBox("The agencies file specified in general options does not exist or could not be loaded." & vbCrLf & "Would you like to try loading the default?", MsgBoxStyle.YesNo, "Could not load Agencies file") = MsgBoxResult.Yes Then
                If agenciesdialog.loadFile("agencies.xml") Then
                    agenciesdialog.ShowDialog()
                Else
                    MsgBox("There was an error loading the agencies file.")
                End If
            End If
        Else
            MsgBox("There was an error loading the agencies file.")
        End If
    End Sub

    'Private Sub chkHoldPatronPhone_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    chkHoldPatronPhoneSize.Enabled = chkHoldPatronPhone.Checked
    'End Sub

    Private Sub chkCheckInOff_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkCheckInOff.CheckedChanged
        chkCheckInAddPhone.Enabled = Not chkCheckInOff.Checked
        cboPaymentMaskBarcode.Enabled = Not chkCheckInOff.Checked
        lblPaymentMaskBarcode.Enabled = Not chkCheckInOff.Checked
    End Sub


End Class
